<template>
 <div>
     <el-form :inline="true" :model="searchInfo" ref="searchInfo">
         <el-form-item label="用户名">
             <el-input v-model="searchInfo.user_name" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery" disabled/>
         </el-form-item>
         <el-form-item label="服务器IP">
             <el-input v-model="searchInfo.ssh_ip_address" placeholder="请输入服务器IP" clearable @keyup.enter.native="handleQuery"/>
         </el-form-item>
         <el-form-item>
             <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
         </el-form-item>
     </el-form>
     <el-form>
         <el-form-item>
             <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="createJumpServerByUser()">添加机器</el-button>
             <el-button @click="deleteBatchJumpServerByUser()" icon="el-icon-delete" :disabled="multiple"  type="danger">批量删除</el-button>
         </el-form-item>
     </el-form>
     <el-table
             :data="tableData"
             row-key="ID"
             @selection-change="handleSelectionChange"
             border
             ref="multipleTable"
             tooltip-effect="dark"
             style="width: 100%">
         <el-table-column type="selection" width="50" align="center"></el-table-column>
         <el-table-column label="ID" width="50" align="center" prop="ID">
             <template slot-scope="scope">{{scope.row.ID}}</template>
         </el-table-column>
         <el-table-column prop="user_name" label="用户名"/>
         <el-table-column prop="virtual_code" label="服务器名称"></el-table-column>
         <el-table-column prop="virtual_alias" label="服务器别名"></el-table-column>
         <el-table-column prop="ssh_ip_address" label="ip地址" min-width="150"/>
         <el-table-column prop="ssh_port" label="端口"/>
         <el-table-column prop="ssh_user" label="系统用户"></el-table-column>
         <el-table-column prop="project.project_fullname" label="项目"></el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
             <template slot-scope="scope">
                 <el-button @click="consoleJumpServerByUser(scope.row)" size="small" type="primary">Console</el-button>
                 <el-button @click="updateJumpServerByUser(scope.row)" size="small" type="primary">添加别名</el-button>
                 <el-button @click="deleteJumpServerByUser(scope.row)" type="danger" icon="el-icon-delete" style="margin-left: 6px;" size="mini" >删除</el-button>
             </template>
         </el-table-column>
     </el-table>
     <el-pagination
             :current-page="page"
             :page-size="pageSize"
             :page-sizes="[10, 30, 50, 100]"
             :style="{float:'right',padding:'20px'}"
             :total="total"
             @current-change="handleCurrentChange"
             @size-change="handleSizeChange"
             layout="total, sizes, prev, pager, next, jumper"
     ></el-pagination>
     <el-dialog :title="dialogTitle"  :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="850px"  @close="closeDialog">
         <el-form ref="appsForm" :model="formData" :rules="rules" size="medium" label-width="110px">
             <el-row :gutter="10">
                 <el-col :span="20" :offset="2">
                     <el-col :span="12">
                         <el-form-item label="用户名称" prop="user_name">
                             <el-input v-model="formData.user_name" prefix-icon="el-icon-info" placeholder="请输入用户名称" clearable disabled></el-input>
                         </el-form-item>
                     </el-col>
                     <el-col :span="12">
                         <el-form-item label="系统用户" prop="os_user">
                             <el-select  placeholder="请选择"  v-model="formData.os_user" style="width:100%">
                                 <el-option
                                         v-for="dict in OsUserOptions"
                                         :key="dict.item_value"
                                         :label="dict.item_name"
                                         :value="dict.item_value"
                                 ></el-option>
                             </el-select>
                         </el-form-item>
                     </el-col>
                     <el-col :span="24">
                         <el-form-item label="服务器选择">
                             <el-transfer
                                     v-model="VirtualValue"
                                     :props="{
                                          key: 'value',
                                          label: 'desc'
                                        }"
                                     :right-default-checked="VirtualValue"
                                     :button-texts="['左边', '右边']"
                                     :titles="['项目服务器', '使用服务器']"
                                     :data="VirtualData"
                             >
                             </el-transfer>
                         </el-form-item>
                     </el-col>
                 </el-col>
             </el-row>
         </el-form>
         <div class="dialog-footer" slot="footer">
             <el-button @click="closeDialog">取 消</el-button>
             <el-button @click="enterDialog" type="primary">确 定</el-button>
         </div>
     </el-dialog>
     <el-dialog :title="dialogAliasTitle"  :close-on-click-modal="false" :visible.sync="dialogAliasFormVisible" width="600px"  @close="closeDialogAlias">
         <el-form ref="appsAliasForm" :model="formAliasData" :rules="rules" size="medium" label-width="110px">
             <el-row :gutter="10">
                 <el-col :span="20" :offset="2">
                     <el-col :span="24">
                         <el-form-item label="服务器别名" prop="virtual_alias">
                             <el-input v-model="formAliasData.virtual_alias" prefix-icon="el-icon-info" placeholder="请输入服务器别名" clearable></el-input>
                         </el-form-item>
                     </el-col>
                 </el-col>
             </el-row>
         </el-form>
         <div class="dialog-footer" slot="footer">
             <el-button @click="closeDialogAlias">取 消</el-button>
             <el-button @click="enterDialogAlias" type="primary">确 定</el-button>
         </div>
     </el-dialog>
 </div>
</template>

<script>
    import {
        createJumpServerUser,
        updateJumpServerUser,
        deleteJumpServerUser,
        getJumpServerUserList,
        deleteJumpServerUserByIds,
    }from "@/api/jump_server_user";
    import { getServersByProjectsList }  from "@/api/cmdb_server";
    import infoList from '@/mixins/infoList'
    export default {
        name: "jumpServerUser",
        mixins: [infoList],
        data() {
            return {
                OsUserOptions: [
                    {
                      item_name: "OS_DEVUSER",
                      item_value: "os_devuser"
                    },
                    {
                        item_name: "OS_APPUSER",
                        item_value: "os_appuser"
                    },
                ],
                VirtualData: [],
                VirtualValueData: [],
                VirtualValue: [],
                transferDate: [],
                dialogFormVisible: false,
                multipleSelection: [],
                multiple: true,
                dialogTitle: "添加服务器",
                dialogAliasTitle: "添加服务器别名",
                dialogAliasFormVisible: false,
                listApi: getJumpServerUserList,
                searchInfo: {
                    user_name: null,
                    ssh_ip_address:null
                },
                formAliasData:{
                    id:null,
                    user_name: null,
                    virtual_alias:null
                },
                formData: {
                    user_name: null,
                    os_user: null,
                    virtualCodeInfos: []
                },
                rules: {
                    os_user: [{ required: true,  message: '请选择系统账户', trigger: 'blur' }],
                    virtual_alias: [{ required: true,  message: '请输入服务器别名', trigger: 'blur' }],
                }

            }
        },
        async created() {
            await this.getSearch()
        },
        methods: {
            //初始化查询数据
            async getSearch(){
                let list = localStorage.getItem("vuex");
                this.searchInfo.user_name = JSON.parse(list).user.userInfo.username
                await this.getTableData();
            },
            handleSelectionChange(selection) {
                this.multiple = !selection.length
                this.multipleSelection = selection
            },
            //批量数据删除
            deleteBatchJumpServerByUser() {
                if(this.multipleSelection.length == 0) {
                    this.$message({
                        type: 'error',
                        message: '请先选择要删除的项！'
                    })
                    return false
                }
                this.$confirm("此操作将永久删除选择数据, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(async () => {
                        const ids = []
                        this.multipleSelection &&
                        this.multipleSelection.map(item => {
                            ids.push(item.ID)
                        });
                        const res = await deleteJumpServerUserByIds({ ids });
                        if (res.code == 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            await this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },
            // 项目搜索
            handleQuery() {
                this.getTableData()
            },
            unique(arr) {
                const res = new Map();
                return arr.filter((arr) => !res.has(arr.ID) && res.set(arr.ID, 1));
            },
            closeDialog(bool) {
                bool && this.getTableData()
                this.$refs['appsForm'].resetFields()
                this.dialogFormVisible = false
            },
            closeDialogAlias(bool) {
                bool && this.getTableData()
                this.$refs['appsAliasForm'].resetFields()
                this.dialogAliasFormVisible = false
            },
            deleteJumpServerByUser(row) {
                this.$confirm("此操作将永久删除该应用, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(async () => {
                        this.visible = false;
                        const res = await deleteJumpServerUser({ ID: row.ID });
                        if (res.code == 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            await this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            },
            async enterDialog() {
                this.$refs['appsForm'].validate(async valid => {
                    if (!valid) return
                    let res;
                    this.transferDate = []
                    for (let i = 0;i < this.VirtualValue.length;i++){
                        this.transferDate.push({
                            virtual_code : this.VirtualValue[i],
                        })
                    }
                    this.formData.virtualCodeInfos = this.transferDate
                    switch (this.type) {
                        case "create":
                            res = await createJumpServerUser(this.formData);
                            this.closeDialog(true)
                            break;
                        default:
                            res = await createJumpServerUser(this.formData);
                            this.closeDialog(true)
                            break;
                    }
                    if (res.code == 0) {
                        this.$message({
                            type:"success",
                            message:"创建/更改成功"
                        })
                        this.closeDialog(true);
                        await this.getTableData();
                    }
                })

            },
            async enterDialogAlias() {
                this.$refs['appsAliasForm'].validate(async valid => {
                    if (!valid) return
                    let res;
                    switch (this.type) {
                        case "update":
                            res = await updateJumpServerUser(this.formAliasData);
                            this.closeDialogAlias(true)
                            break;
                        default:
                            res = await updateJumpServerUser(this.formAliasData);
                            this.closeDialogAlias(true)
                            break;
                    }
                    if (res.code == 0) {
                        this.$message({
                            type:"success",
                            message:"创建/更改成功"
                        })
                        this.closeDialogAlias(true);
                        await this.getTableData();
                    }
                })

            },
            async consoleJumpServerByUser(row){
                let routeUrl = this.$router.resolve({
                         path: "/jump/user/jumpServerWeb/",
                         query: {id:row.ID}
                   });
                   window.open(routeUrl.href, '_blank');
            },
            async updateJumpServerByUser(row){
                this.dialogAliasTitle = '添加|更新服务器别名'
                this.type = 'update';
                this.formAliasData.id =row.ID
                this.formAliasData.user_name = row.user_name
                this.formAliasData.virtual_alias = row.virtual_alias
                this.dialogAliasFormVisible = true;
            },
            async createJumpServerByUser(){
                this.dialogTitle = '添加服务器'
                this.type = 'create';
                this.dialogFormVisible = true;
                let userData = localStorage.getItem("vuex");
                this.formData.user_name = JSON.parse(userData).user.userInfo.username
                const  res = this.getProjectAuthList()
                this.VirtualData=[];
                getServersByProjectsList({'page':1, 'pageSize': 100,'projectCasbinInfos': res.projectCasbinInfos}).then(response => {
                    let list=this.unique(response.data.list);
                    for (let i = 0;i < list.length;i++){
                        this.VirtualData.push({
                            value : list[i].virtual_code,
                            desc: list[i].ip_address,
                        })
                    }
                })
                this.VirtualValue=[];
                getJumpServerUserList({'page':1, 'pageSize': 10,'user_name':this.formData.user_name}).then(response => {
                    let list=response.data.list;
                    list.map((item) => {
                        this.VirtualValue.push(item.virtual_code)
                    })
                })
            }
        },
    }
</script>

<style scoped>

</style>
